/*
 * Base.cpp
 *
 *  Created on: 29/05/2012
 *      Author: lucho0
 */

#include "Base.h"
#include "PlayScenarioPanel.h"
#include "Explosion.h"


void Base::createLives()
{
	flagger->addFlag(new Flag(relativePositionX-LIVES_POSX_FIX,relativePositionY-LIVES_POSY_FIX,LIVES_DEFAULT_IMAGE,this,"lives"));
}

Base::Base(std::string userName, int posX, int posY, int fontSize,
		std::string imageSurface, Widget* parent) :
	WidgetMovimiento(SHIP_BASE, posX, posY,imageSurface,parent,BASE_DEFAULT_DAMAGE), WidgetSonido(BASE_DEFAULT_SOUND_EFFECT) {

	this->owner = userName;
	this->lives = PLAYER_DEFAULT_LIVES;
	this->image = imageSurface;

	relativePositionX = this->parcel->width/2;
	relativePositionY = this->parcel->height/2;

	// Fix username size to 12 on base

	userName.resize(12);

	//Color RGB las 3 parameters

	this->userName = new Label(userName,14,this,relativePositionX,relativePositionY,255,255,255);

	this->fontSize = fontSize;

	this->progressBar = new ProgressBar(BASE_DEFAULT_ENERGY, relativePositionX-PROGRESS_BAR_POSX_FIX, relativePositionY+PROGRESS_BAR_POSY_FIX , this);

	this->flagger = new Flagger();

	//Create lives
	for(int i=0; i < lives; i++){
		createLives();
	}
}

void Base::showOn(SDL_Surface* surface) {

	if(surfaceShown != NULL){
		SDL_FreeSurface(surfaceShown);
		surfaceShown = NULL;
	}
	surfaceShown = SurfaceUtils::rotateSurface(this->surface, 0);

	this->progressBar->showOn(surfaceShown);
	flagger->showOn(surfaceShown);
	userName->showOn(surfaceShown);
	WidgetMovimiento::showOn(surface);
}

int Base::getLives() {
	return this->lives;
}

void Base::reduceLives() {
	if (this->lives > 0) {
		this->lives -=1 ;
	} else{
		this->lives = 0;
	}

	this->flagger->deleteFlag("lives");

	if(lives<=0){
		// GAME OVER
		if(((PlayScenarioPanel*)parent)->getOwner() == owner){
			((PlayScenarioPanel*)parent)->gameover(true);
		}else{
			((PlayScenarioPanel*)parent)->gameover(false);
		}
	}

}

void Base::handleColision(WidgetMovimiento* with){

	if( with->getType() == SHIP || with->getType() == AMMO ){
		reduceEnergy(with->getDamage());
		playSound();

		if(isDead()) {
			((PlayScenarioPanel*)parent)->add(new Explosion(this->parcel->posX,this->parcel->posY,parent));
			// GAME OVER
			if(((PlayScenarioPanel*)parent)->getOwner() == owner){
				((PlayScenarioPanel*)parent)->gameover(true);
			}else{
				((PlayScenarioPanel*)parent)->gameover(false);
			}
		}
	}
}

void Base::updateStatus(int lives,int energyPorcent){

	if(lives != this->lives){
		while(this->lives > 0 ){
			this->flagger->deleteFlag("lives");
			this->lives--;
		}

		while(this->lives < lives){
			createLives();
		}

		this->lives = lives;
	}

	this->progressBar->resetBar(energyPorcent);
}

bool Base::isDead(){
	return this->progressBar->getPorcent() <= 0;
}


void Base::reduceEnergy(int value) {
	this->progressBar->reducePercent(value);
}

int Base::getEnergy() {
	return this->progressBar->getPorcent();
}
Base::~Base() {
	delete progressBar;
}
